from myelin.Ns import MYELINS, MYELIN
from myelin.server.core.ft import ModelDriver

from nodetypes.formats.mml.Events import Form
from nodetypes.models.Graph import GraphDocument
from nodetypes.Ns import GRAPHS_NS
from nodetypes.lib import Utils

from nodetypes import config

#DefaultNsMapString = u''.join([
#    u'%s = %s\n' % (k,v)
#    for k,v in config.DEFAULT_SPARQL_NSMAP.iteritems()
#])
#try:
#    del k,v
#except:
#    pass

class Form(Form):
    
    newGraphDocument        = GraphDocument.Retrieve
    newGraphDriver          = GraphDocument.Initialize
    
    #defaultNsMapString = DefaultNsMapString
    defaultPrettyMethods = config.DEFAULT_PRETTY_METHODS
    
    defaultSubmitAction = u'query'
    
    def createInstance(self, context, node):
        #defaults = context.defaults
        #map = context.uriMapper.apply
        
        eventData = context.event.data
        model = context.model
        
        nxa = node.xml_append
        nxc = node.xml_create_element
        
        self.createMethodOptions(
            context,
            nxa(
                nxc(
                    u'a:method', MYELINS
                )            
            ),
            (context.nodeType.actions.get(self.defaultSubmitAction) or {}).keys()
        ) 
        
        nxa(
            nxc(
                u'a:graph-result-method', MYELINS
            )
        )
        
        self.createDefaultGraphsOptions(
            context,
            nxa(
                nxc(
                    u'a:default-graphs', MYELINS
                )
            )
        )
        
        nxa(
            nxc(
                u'a:default-graph-uri', MYELINS
            )
        )
        
        nxa(
            nxc(
                u'a:named-graph-uri', MYELINS
            )
        )
        
        if context.method in self.defaultPrettyMethods:
            nxa(
                nxc(
                    u'a:nsmaps', MYELINS,
                    content = eventData.config.defaultNsMapString 
                )
            )
        else:
            nxa(
                nxc(
                    u'a:nsmaps', MYELINS
                )
            )
        
        nxa(
            nxc(
                u'a:query', MYELINS
            )
        )        
        
        return node
    
    def createDefaultGraphsOptions(self, context, node):
        repo = context.repo
        eventData = context.event.data
        
        newGraphDoc = self.newGraphDocument
        newGraphDriver = self.newGraphDriver
        
        locale = context.preferences['locale']
        acls = context.acls.checkNodeAcls
        umap = context.uriMapper.apply
        
        nxa = node.xml_append
        nxc = node.xml_create_element
        
        for k,g in eventData.config.defaultRdfGraphs.iteritems():            
            #print "RESET: ", (k,g.descUri)
            if not g.descUri:
                nxa(
                    nxc(
                        u'a:option', MYELINS,
                        attributes = {
                            u'key'  : unicode(k),
                        },
                        content = unicode(k)
                    )
                )
                continue
            g = repo.fetchResourceByUri(g.descUri)
            s = g.getAbsolutePathAsUri()
            m = newGraphDoc(
                newGraphDriver(g.getModel().driver),
                g.uri,
                s, s
            )
                
            if locale not in m.dcLanguage:
                for t in m.mTranslation:
                    if locale in t.dcLanguage:
                        m = t
                        break
            alt = m.rdf_join('dcAlternative')
            if alt:
                title = m.rdf_join('dcTitle')
                if title:
                    if len(alt) < len(title):
                        title = alt
                else:
                    title = alt
            else:
                title = m.rdf_join('dcTitle')
                
            if acls(m.rdf_domain,'view'):
                nxa(
                    nxc(
                        u'a:option', MYELINS,
                        attributes = {
                            u'key'  : unicode(k),
                            u'uri'  : umap(m.rdf_domain),
                        },
                        content = title or unicode(k)
                    )
                )
            
    
    #def createDefaultGraphsOptions(self, context, node, eventData):
    #    server = context.server
    #    
    #    driver = context.server.graphs.get(GRAPHS_NS + 'site')
    #    if driver:
    #        driver = self.newModelDriver(
    #            context.repo,
    #            reduce(lambda a,b:a+b,driver.values(),[])
    #        )
    #    else:
    #        driver = context.dbDriver
    #    
    #    locale = context.preferences['locale']
    #    acls = context.acls.checkNodeAcls
    #    umap = context.uriMapper.apply
    #    
    #    graphs = {}
    #    pred = MYELIN + u'for-graph'
    #    
    #    newGraph = self.newGraphDocument
    #    
    #    nxa = node.xml_append
    #    nxc = node.xml_create_element
    #    
    #    for uri, modelList in server.defaultQueryGraphs.iteritems():
    #        # CHECK ACLS?
    #        # - not really necessary since it will be checked when it is being executed
    #        if not modelList.descUri:
    #            print "ML NOT: ", uri, modelList
    #            # NOTICE: this updates the global server config (ie. caches the value)
    #            for m in driver.complete(None,pred,uri,None,None):    
    #                modelList.descScope = m[4].split('#')[0]
    #                modelList.descUri = m[0]
    #                break
    #            else:
    #                continue
    #        
    #        m = newGraph(
    #            driver,
    #            modelList.descUri,
    #            modelList.descScope,
    #            modelList.descScope
    #        )
    #            
    #        if locale not in m.dcLanguage:
    #            for t in m.mTranslation:
    #                if locale in t.dcLanguage:
    #                    m = t
    #                    break
    #        alt = m.rdf_join('dcAlternative')
    #        if alt:
    #            title = m.rdf_join('dcTitle')
    #            if title:
    #                if len(alt) < len(title):
    #                    title = alt
    #            else:
    #                title = alt
    #        else:
    #            title = m.rdf_join('dcTitle')
    #            
    #        if acls(m.rdf_domain,'view'):
    #            nxa(
    #                nxc(
    #                    u'a:option', MYELINS,
    #                    attributes = {
    #                        u'key'  : unicode(uri),
    #                        u'uri'  : umap(m.rdf_domain),
    #                    },
    #                    content = title or unicode(uri)
    #                )
    #            )